# -*- coding: utf-8 -*-
import os
import Models
import MasterPage
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    
    def get(self):
        user = GetUser(self)

        userRSS = db.GqlQuery("SELECT * FROM UserRSS WHERE Email = :author", author=user.email())

        url = ''
        if userRSS.count() > 0:
            url = userRSS[0].RSS
			
        header = MasterPage.OutputHeader(user)
	footer = MasterPage.OutputFooter()
		
        template_values = {'header': header, 'footer': footer, 'nickname': user.nickname(),'url': url}
   
        path = os.path.join(os.path.dirname(__file__), 'html/RegSMS.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        user = GetUser(self)

        rssurl = self.request.POST.get('rssurl')

        userRSS = db.GqlQuery("SELECT * FROM UserRSS WHERE Email = :author", author=user.email())
        if userRSS.count() > 0:
            userRSS = userRSS[0]
        else:
            userRSS = Models.UserRSS(Email = user.email())
            
        userRSS.RSS = rssurl
        userRSS.put()
        
        message = "Subscribe successfully!"
		
        header = MasterPage.OutputHeader(user)
	footer = MasterPage.OutputFooter()
		
        template_values = {'header': header, 'footer': footer, 'nickname': user.nickname(),'message': message,\
                        'url': rssurl}
 
        path = os.path.join(os.path.dirname(__file__), 'html/RegSMS.html')
        self.response.out.write(template.render(path, template_values))
        
application = webapp.WSGIApplication([('/regsms', MainPage)],debug=True)

def GetUser(self):
    user = users.get_current_user()
    if user:
        self.response.headers['Content-Type'] = 'text/html'
    else:
        self.redirect(users.create_login_url(self.request.uri))
    return user

def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()
